<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="能源类型" prop="energyType">
        <el-select
          v-model="queryParams.energyType"
          clearable
          placeholder="请选择能源类型"
        >
          <el-option
            v-for="item in energyTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单价名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入单价名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['device:costUnit:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['device:costUnit:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Search" @click="toggleSearch">{{
          showSearch ? "隐藏搜索" : "显示搜索"
        }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="getList"
          >刷新</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="min-height: 500px; height: 650px"
    >
      <el-table-column
        prop="name"
        align="center"
        label="单价名称"
        width="250"
        show-overflow-tooltip
      />
      <el-table-column
        prop="costUnit"
        align="center"
        label="单价单位"
        width="120"
      />
      <el-table-column
        label="能源类型"
        align="center"
        prop="energyType"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="getEnergyTypeTagType(scope.row.energyType)">
            {{ getEnergyTypeName(scope.row.energyType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" align="center" label="单价(元)" width="120">
        <template #default="scope">
          <span style="color: #e6a23c; font-weight: 600">
            ¥{{ scope.row.price?.toFixed(2) || "0.00" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="carbonStanTonCoal"
        align="center"
        label="标吨煤"
        width="150"
      >
        <template #default="scope">
          <span style="color: #67c23a; font-weight: 600">
            {{ scope.row.carbonStanTonCoal?.toFixed(10) || "0.0000000000" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="sortOrder"
        align="center"
        label="排序"
        width="80"
      />
      <el-table-column
        prop="createAt"
        align="center"
        label="创建时间"
        width="250"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ formatDate(scope.row.createAt) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="updateAt"
        align="center"
        label="更新时间"
        width="250"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ formatDate(scope.row.updateAt) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:costUnit:edit']"
            >修改</el-button
          >
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:costUnit:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改能源单价对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="50%"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="costUnitRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单价名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入单价名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价单位" prop="costUnit">
              <el-input v-model="form.costUnit" placeholder="请输入单价单位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="能源类型" prop="energyType">
              <el-select
                v-model="form.energyType"
                placeholder="请选择能源类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in energyTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价(元)" prop="price">
              <el-input-number
                v-model="form.price"
                :precision="2"
                :min="0"
                :max="999999.99"
                placeholder="请输入单价"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标吨煤" prop="carbonStanTonCoal">
              <el-input-number
                v-model="form.carbonStanTonCoal"
                :precision="10"
                :min="0"
                :max="9999999999.9999999999"
                placeholder="请输入标吨煤"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number
                v-model="form.sortOrder"
                :min="0"
                :max="9999"
                placeholder="请输入排序"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
            v-hasPermi="['device:costUnit:save']"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @current-change="currentChange"
      :current-page="pagination.curPage"
      :page-size="pagination.pageSize"
      layout="total, prev, pager, next"
      :total="pagination.total"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getCostUnitList,
  getCostUnit,
  addCostUnit,
  updateCostUnit,
  saveCostUnit,
  delCostUnit,
  exportCostUnit,
} from "@/api/deviceManage/costUnit";
import {
  ENERGY_TYPE_OPTIONS,
  getEnergyTypeName,
  getEnergyTypeTagType,
} from "@/utils/enums";

const { proxy } = getCurrentInstance();

// 响应式数据
const tableData = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");

// 查询参数
const queryParams = reactive({
  name: "",
  energyType: null,
});

// 分页参数
const pagination = reactive({
  curPage: 1,
  pageSize: 10,
  total: 0,
});

// 能源类型选项
const energyTypeOptions = ENERGY_TYPE_OPTIONS.filter(
  (item) => item.value !== 20
); // 排除电力

// 表单数据
const form = reactive({
  id: null,
  name: "",
  costUnit: "",
  energyType: null,
  price: 0,
  carbonStanTonCoal: 0,
  sortOrder: 0,
});

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: "单价名称不能为空", trigger: "blur" }],
  costUnit: [{ required: true, message: "单价单位不能为空", trigger: "blur" }],
  energyType: [
    { required: true, message: "能源类型不能为空", trigger: "change" },
  ],
  price: [
    { required: true, message: "单价不能为空", trigger: "blur" },
    { type: "number", min: 0, message: "单价必须大于等于0", trigger: "blur" },
  ],
  carbonStanTonCoal: [
    { type: "number", min: 0, message: "标吨煤必须大于等于0", trigger: "blur" },
  ],
  sortOrder: [
    { type: "number", min: 0, message: "排序必须大于等于0", trigger: "blur" },
  ],
});

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
}

/** 查询列表 */
function getList() {
  loading.value = true;
  let params = { ...pagination, ...queryParams };
  getCostUnitList(params)
    .then((response) => {
      tableData.value = response.data.list || [];
      pagination.total = response.data.totalCount || 0;
      loading.value = false;
    })
    .catch((error) => {
      console.error("获取能源单价列表失败:", error);
      loading.value = false;
      ElMessage.error("获取能源单价列表失败，请稍后重试");
    });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  Object.assign(form, {
    id: null,
    name: "",
    costUnit: "",
    energyType: null,
    price: 0,
    carbonStanTonCoal: 0,
    sortOrder: 0,
  });
  proxy.resetForm("costUnitRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  pagination.curPage = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.name = "";
  queryParams.energyType = null;
  handleQuery();
}

/** 切换搜索显示/隐藏 */
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增能源单价";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getCostUnit(row.id).then((res) => {
    Object.assign(form, res.data);
    // 确保 carbonStanTonCoal 字段有值，如果为 null 或 undefined 则设置为 0
    if (
      form.carbonStanTonCoal === null ||
      form.carbonStanTonCoal === undefined
    ) {
      form.carbonStanTonCoal = 0;
    }
    open.value = true;
    title.value = "修改能源单价";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["costUnitRef"].validate((valid) => {
    if (valid) {
      if (form.id) {
        updateCostUnit(form).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCostUnit(form).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm(
    '是否确认删除名称为"' + row.name + '"的数据项?',
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      delCostUnit([row.id]).then((res) => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "intra/config/costunit/toExport",
    {
      ...queryParams,
    },
    `能源单价_${new Date().getTime()}.xlsx`
  );
}

/** 分页变化 */
function currentChange(e) {
  pagination.curPage = e;
  getList();
}

// 页面初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";

.app-container {
  padding: 10px 20px;
  background: $base-menu-background;
  min-height: 100vh;
}

// 搜索表单样式
.el-form {
  background: #ffffff;
  padding: 10px 20px;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &:not(.el-button--primary) {
      background: linear-gradient(135deg, #909399 0%, #73767a 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #82848a 0%, #6c6e72 100%);
        color: #ffffff;
      }
    }
  }
}

// 按钮组样式
.mb8 {
  margin-bottom: 10px;
  margin-left: 0 !important;
  margin-right: 0 !important;
  background: #ffffff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &.el-button--primary.is-plain {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &.el-button--success.is-plain {
      background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
        color: #ffffff;
      }
    }
  }
}

// 操作按钮样式
:deep(.el-button--text) {
  color: #4fdaca !important;
  font-weight: 600 !important;
  position: relative !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  border-radius: 6px !important;
  padding: 6px 12px !important;

  &:hover {
    color: #32b7cb !important;
    background: linear-gradient(
      135deg,
      rgba(79, 218, 202, 0.1) 0%,
      rgba(50, 183, 203, 0.1) 100%
    ) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 2px 8px rgba(79, 218, 202, 0.2) !important;
  }

  &:active {
    transform: translateY(0) !important;
    box-shadow: 0 1px 4px rgba(79, 218, 202, 0.3) !important;
  }
}

// 更具体的操作按钮样式选择器
::v-deep(.el-button.el-button--text) {
  color: #4fdaca !important;
  font-weight: 600 !important;
  font-size: 13px !important;
  padding: 8px 16px !important;
  margin: 0 6px !important;
  border-radius: 8px !important;
  border: 1px solid transparent !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  position: relative !important;
  overflow: hidden !important;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
    transition: left 0.3s ease;
    z-index: -1;
  }

  &:hover {
    color: #ffffff !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 12px rgba(79, 218, 202, 0.4) !important;
    border-color: #4fdaca !important;
    background: transparent !important;

    &::before {
      left: 0;
    }
  }

  &:active {
    transform: translateY(0) !important;
    box-shadow: 0 2px 6px rgba(79, 218, 202, 0.3) !important;
  }
}

.el-select {
  width: 220px !important;
}
.el-input {
  width: 100% !important;
}
.el-input-number {
  width: 100% !important;
}

// 表格样式
.main-table {
  width: 100%;

  // 表头样式优化
  :deep(.el-table th) {
    padding: 8px 0;
    background: #f8f9fa;
    font-weight: 600;
    white-space: nowrap; // 防止表头文字换行
    text-overflow: ellipsis;
    overflow: hidden;
  }

  // 表格单元格样式优化
  :deep(.el-table td) {
    padding: 8px 0;
    white-space: nowrap; // 防止单元格内容换行
    text-overflow: ellipsis;
    overflow: hidden;
  }

  // 固定列样式
  ::v-deep(.el-table__fixed-right) {
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
    z-index: 20;

    .el-table__header-wrapper {
      z-index: 11;
      position: relative;
    }

    .el-table__body-wrapper {
      z-index: 10;
      position: relative;
    }

    // 确保表头单元格正确显示
    .el-table__header th {
      background: #f8f9fa !important;
      position: relative;
      z-index: 12;
    }
  }

  :deep(.el-table__fixed-left) {
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
    z-index: 10;

    .el-table__header-wrapper {
      z-index: 11;
      position: relative;
    }

    .el-table__body-wrapper {
      z-index: 10;
      position: relative;
    }

    // 确保表头单元格正确显示
    .el-table__header th {
      background: #f8f9fa !important;
      position: relative;
      z-index: 12;
    }
  }

  // 操作按钮在固定列中的样式
  :deep(.el-table__fixed-right .el-button--text) {
    font-size: 12px !important;
    padding: 4px 8px !important;
    margin: 0 2px !important;
    color: #4fdaca !important;
    font-weight: 600 !important;

    &:hover {
      color: #32b7cb !important;
      background: linear-gradient(
        135deg,
        rgba(79, 218, 202, 0.1) 0%,
        rgba(50, 183, 203, 0.1) 100%
      ) !important;
    }
  }
}

// 对话框样式
:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);

  .el-dialog__header {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px 12px 0 0;
    padding: 20px 24px;
    border-bottom: 1px solid #e4e7ed;

    .el-dialog__title {
      font-weight: 600;
      color: #2c3e50;
      font-size: 16px;
    }
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    padding: 16px 24px;
    background: #f8f9fa;
    border-radius: 0 0 12px 12px;
    border-top: 1px solid #e4e7ed;

    .el-button {
      border-radius: 6px;
      font-weight: 500;
      padding: 8px 20px;

      &.el-button--primary {
        background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
        border: none;
        color: #ffffff;

        &:hover {
          background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
          color: #ffffff;
        }
      }

      &:not(.el-button--primary) {
        background: #ffffff;
        border: 1px solid #dcdfe6;
        color: #606266;

        &:hover {
          background: #f5f7fa;
          border-color: #c0c4cc;
          color: #606266;
        }
      }
    }
  }
}

// 分页样式
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: center;

  .el-pagination__total {
    color: #606266;
    font-weight: 500;
  }

  .btn-prev,
  .btn-next {
    border-radius: 6px;
    border: 1px solid #dcdfe6;
    background: #ffffff;
    color: #606266;

    &:hover {
      color: #4fdaca;
      border-color: #4fdaca;
    }
  }

  .el-pager li {
    border-radius: 6px;
    margin: 0 2px;
    border: 1px solid #dcdfe6;
    background: #ffffff;
    color: #606266;

    &:hover {
      color: #4fdaca;
      border-color: #4fdaca;
    }

    &.is-active {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border-color: #4fdaca;
      color: #ffffff;
    }
  }
}
</style>
